# !/usr/bin/python3
# coding:utf-8

import time
import requests

share_id_lst = ['sh601318', 'sz002230', 'sz300059']
catch_interval = 0.5

url = 'http://hq.sinajs.cn/list='
for share_id in share_id_lst:
    url += share_id + ','
url.rstrip(',')

while 1:
    try:
        request = requests.get(url)
        info_lst = request.text.split('\n')
        for i, share_id in enumerate(share_id_lst):
            with open('share_data_%s.csv' % share_id, 'a') as fp:
                time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                print('get %s at %s' % (share_id, time_str))

                # 整理CSV格式
                info = info_lst[i].lstrip('var hq_str_%s="' % share_id)
                info = info.rstrip('";')
                info = '%s,%s' % (share_id, info)
                fp.write(info + '\n')
    except:
        time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        print('failed to get info at %s, failed text: %s' % (time_str, request.text))
    finally:
        time.sleep(catch_interval)
